package com.shujia.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class wordcountdemo {
    public static class Mymap extends Mapper<LongWritable,Text,Text,LongWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String s = value.toString();
            String[] split = s.split(" ");

            for (String s1 : split) {
                Text word = new Text(s1);
                context.write(word,new LongWritable(1L));
            }
        }
    }

    public static class Myreduce extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {

            Long sum = 0L;
            for (LongWritable value : values) {
                long num = value.get();
                sum+=num;
            }
            context.write(key,new LongWritable(sum));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //获取hadoop的配置文件
        Configuration conf = new Configuration();
        //创建job任务
        Job job = Job.getInstance(conf, wordcountdemo.class.getSimpleName());
        //获取job运行主类
        job.setJarByClass(wordcountdemo.class);
        //设置数据读取路径
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        //设置map类
        job.setMapperClass(Mymap.class);
        //设置map的输出key和value的类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce类
        job.setReducerClass(Myreduce.class);
        //设置reduce输出的数据类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //指定输出的HDFS路径
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        job.waitForCompletion(true);
    }

}
